<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="/WEB-INF/jsp/fragments/taglibs.jsp" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>流程定义</title>
    <meta name="decorator" content="default"/>
    <style>
        #taskPanels .accordion-header-selected {
            background: #e0ecff;
        }

        #taskPanels .accordion-header-selected .panel-title {
            color: #674d4d;
        }
    </style>
    <c:set value="${lsFn:getAidMems(param.planId)}" var="aidMems"/>
    <c:set value="${lsFn:getNoOutNodes(param.planId)}" var="noOutNodes"/>
    <c:set value="${lsFn:getExistNodes(param.planId)}" var="existNodes"/>
    <c:set value="${param.stepType != null ? param.stepType : (stepInfo != null ? stepInfo.type : 0)}" var="stepType"/>
    <c:set value="${param.stepId != null ? param.stepId : (stepInfo != null ? stepInfo.id : -1)}" var="stepId"/>
    <script>
        var stepInfo = ${stepInfoJson == null ? '""' : stepInfoJson};
        var stepId = '${stepId}';
        var stepType = '${stepType}';
    </script>
</head>
<body>
<div class="easyui-layout" data-options="fit:true" style="margin: 5px">
    <div data-options="region:'west',split:true" style="width:250px;padding:10px">
        <div class="easyui-panel" style="padding: 5px;width: 38px;"
             data-options="style:{marginBottom:5, float:'right'}">
            <a href="#" id="newStep" class="easyui-linkbutton easyui-tooltip" stepType="0" stepId="-1" title="点击新建环节" style="float: right;"
               data-options="plain:true,iconCls:'icon-step-add', <c:if test="${stepId == -1}">selected:true</c:if> "></a>
        </div>
        <div style="clear: both;"></div>

        <c:forEach items="${steps}" var="step">
            <div class="easyui-panel" id="steps_${step.id}" style="padding: 2px;" data-options="style:{marginBottom:5}">
                <a href="javascript:void(0)" stepId="${step.id}" stepType="${step.type}" class="easyui-linkbutton stepBtn"
                   data-options="plain:true<c:if test="${step.id == stepId}">,selected:true</c:if>">${step.typeName}</a>
                【<span class="stepNodes easyui-tooltip" title="当前环节下所有节点"><c:forEach items="${step.nodes}" var="node"
                                                                                     varStatus="st"><c:if
                    test="${!st.last}">${node},</c:if><c:if
                    test="${st.last}">${node}</c:if></c:forEach></span>】
                <c:if test="${step.noOutNodes != null && step.noOutNodes.size() > 0}">
                【<span class="stepNoOutNodes easyui-tooltip" title="当前环节下所有可选进入节点" style="color:red"><c:forEach
                    items="${step.noOutNodes}" var="node" varStatus="st"><c:if test="${!st.last}">${node},</c:if><c:if
                    test="${st.last}">${node}</c:if></c:forEach></span>】
                </c:if>
                <a href="javascript:void(0)" stepId="${step.id}" class="easyui-linkbutton easyui-tooltip delStepBtn"
                   title="点击删除当前环节" style="float: right;"
                   data-options="plain:true,iconCls:'icon-delete'"></a>
            </div>
        </c:forEach>

    </div>
    <div data-options="region:'center'" style="padding:10px">
        <div class="easyui-panel" style="padding: 2px 2px 5px 2px; border-width:0">
            <select id="stepType" class="easyui-combobox" name="type" label="请选择要创建的环节类型:" labelWidth="150"
                    style="width:300px;">
                <option value="-1"></option>
                <c:forEach items="${lsFn:getEntries('StepType')}" var="item">
                    <option value="${item.code}"
                            <c:if test="${stepType == item.code}">selected</c:if>
                    >${item.name}</option>
                </c:forEach>
            </select>
        </div>

        <div class="easyui-panel" title="" style="" data-options="fit:true">
            <div class="easyui-layout" data-options="fit:true">
                <div data-options="region:'north'" style="height: 50px;padding:10px">
                    <select class="easyui-combobox toValid" id="lastCodes" name="lastCodes" label="请设置进入节点:" labelWidth="100"
                            data-options="<c:if test="${stepType == 3}">multiple: true,
                            validType: 'minSelect[\'input[name=lastCodes]\', 2]'</c:if>" style="width:160px;">
                        <c:forEach items="${noOutNodes}" var="item">
                            <option stepId="${item.stepId}" switch_logic="${item.switch_logic}"
                                    value="${item.code}">${item.code}</option>
                        </c:forEach>
                    </select>

                    <a href="#" id="addSltLast" style="display: none" class="easyui-linkbutton easyui-tooltip"
                       title="点击添加进入节点"
                       data-options="plain:true,iconCls:'icon-link-add',onClick:createSltLast"></a>
                </div>
                <div data-options="region:'center'">
                    <a href="#" id="addNode" class="easyui-linkbutton easyui-tooltip" title="点击添加节点"
                       data-options="plain:true,iconCls:'icon-task-add'" onclick="addTaskPanel()"
                       style="display: none;"></a>
                    <div id="taskPanels" class="easyui-accordion" style="width:100%;height:350px;">
                        <c:forEach items="${(stepType == 1 || stepType == 2) ? [1,2] : [1]}" varStatus="st" var="leeds_">
                            <div title="任务节点" style="overflow:auto;padding:10px; height: 200px;">
                                <div class="easyui-layout" data-options="fit:true">
                                    <form class="taskForm">
                                        <c:choose>
                                            <c:when test="${stepType == 4}">
                                                <div style="margin-bottom:10px">
                                                    <select class="easyui-combobox" name="assignee" label="任务执行人"
                                                            labelWidth="80px" style="width:95%">
                                                        <c:forEach items="${aidMems}" var="item">
                                                            <c:if test="${item.user_id != null}">
                                                                <option value="${item.user_id}">${item.name} - ${item.title}</option>
                                                            </c:if>
                                                        </c:forEach>
                                                    </select>
                                                </div>
                                            </c:when>
                                            <c:otherwise>
                                                <c:if test="${stepType == 1}">
                                                <div data-options="region:'north'" style="border-width:0 0 1px 0;margin-bottom:10px;overflow: hidden; height:62px">
                                                    <div style="margin-bottom:10px">
                                                        <span style="display: inline-block;width: 80px;">选择分支路径</span>
                                                        <input name="taskType" type="radio" value="0" checked>新建
                                                        <input name="taskType" type="radio" value="1">指向已有节点
                                                    </div>
                                                    <div style="margin-bottom:10px;display: none" class="sltExist">
                                                    <select class="easyui-combobox" name="code" label="选择节点" labelWidth="80"
                                                            data-options="" style="width: 300px">
                                                        <c:forEach items="${existNodes}" var="item">
                                                            <option stepId="${item.stepId}" value="${item.code}">${item.code}</option>
                                                        </c:forEach>
                                                    </select>
                                                    </div>
                                                </div>
                                                </c:if>
                                                <div data-options="region:'west'" class="newTask"
                                                     style="width:400px;border-width:0 1px 0 0; padding-right: 10px;">
                                                    <div style="margin-bottom:10px">
                                                        <select class="easyui-combobox" name="assignee" label="任务执行人"
                                                                labelWidth="80px" style="width:95%">
                                                            <c:forEach items="${aidMems}" var="item">
                                                                <c:if test="${item.user_id != null}">
                                                                    <option value="${item.user_id}">${item.name} - ${item.title}</option>
                                                                </c:if>
                                                            </c:forEach>
                                                        </select>
                                                    </div>
                                                    <div style="margin-bottom:10px">
                                                        <input class="easyui-textbox toValid" name="detail" labelWidth="80px"
                                                               style="width:95%;height:100px"
                                                               data-options="label:'任务内容',multiline:true,required:true,validType:'maxLength[250]'">
                                                    </div>
                                                    <div style="margin-bottom:10px">
                                                        <input class="easyui-textbox" name="switch_logic" labelWidth="80px"
                                                               prompt="请输入逻辑语句。如：通知成功。不超过10个字" style="width:90%"
                                                               data-options="label:'分支因素',validType:'maxLength[10]'">与否
                                                    </div>
                                                </div>
                                                <div data-options="region:'center'" class="newTask" style="border-width:0; padding-left: 10px;">
                                                    <div style="margin-bottom:10px">
                                                        <span style="display: inline-block;width: 80px;">操作</span>
                                                        <input name="operation_code" type="radio" value="0" checked>通知
                                                        <input name="operation_code" type="radio" value="1">上报
                                                    </div>
                                                    <div class="noticeDiv">
                                                        <div style="margin-bottom:10px">
                                                            <select class="easyui-combobox" data-options="multiple:true"
                                                                    name="notifiedIds"
                                                                    label="通知对象" labelWidth="80px" style="width:95%">
                                                                <c:forEach items="${aidMems}" var="item">
                                                                    <option value="${item.id}">${item.name} - ${item.title}</option>
                                                                </c:forEach>
                                                            </select>
                                                        </div>
                                                        <div style="margin-bottom:10px">
                                                            <input class="easyui-textbox" name="notifyTpl" labelWidth="80px"
                                                                   style="width:95%;height:100px"
                                                                   prompt="请添加通知模版。如：紧急通知！尊敬的XX领导您好！在XX地点，发生严重交通事故，造成XX伤亡，请您立刻指示，启动应急事项！"
                                                                   data-options="label:'通知模版',multiline:true">
                                                        </div>
                                                    </div>
                                                </div>
                                            </c:otherwise>
                                        </c:choose>
                                    </form>
                                </div>
                            </div>
                        </c:forEach>
                    </div>

                    <div style="text-align:center;padding:5px 0">
                        <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-save'"
                           onclick="saveStep()" style="width:120px">保存</a>
                        <a href="#" id="showProcImg" class="easyui-linkbutton" data-options="iconCls:'icon-image'"
                           onclick="$('#w').window('open')" style="width:120px;<c:if test="${plan.procdef_id==null||plan.procdef_id==''}">display: none;</c:if> ">查看流程图</a>

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div id="w" class="easyui-window" title="流程生成成功" data-options="modal:true,fit:true,closed:true,iconCls:'icon-save'" style="/*width:700px;height:400px;*/padding:10px;">
    <div class="easyui-layout" data-options="fit:true">
        <div data-options="region:'center'" style="padding:10px;">
            <img id="procImg" src="${ctx}/acti/getProcDefImg.do?procDefId=${plan.procdef_id}">
        </div>
        <div data-options="region:'south',border:false" style="text-align:right;padding:5px 0 0;">
            <a class="easyui-linkbutton" data-options="iconCls:'icon-ok'" href="javascript:void(0)" onclick="$('#w').window('close')" style="width:80px">确定</a>
        </div>
    </div>
</div>
<script type="text/javascript">
    var pre = $.parser.onComplete;
    $.parser.onComplete = function () {
        pre()
        renderStep(stepType, stepInfo)
    }

    function initBranch(val) {//0 panel 通过、1 panel 不通过
        var title = '任务节点';
        var newLogic = $('#lastCodes option[value=' + val + ']').attr('switch_logic');
        $.each([0,1], function (i, n) {
            var label = (n == 0 ? newLogic : '未'+newLogic)
            $('#taskPanels').accordion('getPanel', n).panel('setTitle', title + ' | 【' + label + '】时执行')
            $('input[name=label]').eq(n).val(label);
            $('.taskForm').eq(n).append('<input type="hidden" name="exp" value="E==' + n + '"/>');
            $('.taskForm').eq(n).append('<input type="hidden" name="label" value="' + label + '"/>');
        })
    }

    function renderStep(stepType, stepInfo) {
        //1、准备节点
        //分支环节，属性设置
        if(stepInfo == '' && stepType == 1) {
            $('#lastCodes').combobox({
                onChange: function (newVal, oldVal) {
                    initBranch(newVal)
                }
            })
            initBranch($('#lastCodes').val())
        }
        //2、填充数据
        if (stepInfo != '') {
            $('#stepType').combo('disable');

            $('#lastCodes').combobox('setValues', stepInfo.last_codes.split(','))
            $('#lastCodes').combobox('disable');

            $.each($('.taskForm'), function (i, n) {
                var task = stepInfo.tasks[i];
                $(n).form('load', task);

                if (task.operation_code == 1) {
                    $(n).find('.noticeDiv').hide();
                }

                //set panel title
                var p = $('#taskPanels').accordion('getPanel', i);
                var title = '节点编号【 ' + task.code + ' 】';
                if(stepType == 1) {
                    title += ' | 【 ' + task.label +' 】时执行';
                }
                p.panel('setTitle', title);

            })
        }

        //ajax方式过于复杂，暂时作为将来优化版本考虑
        //2、加载数据
    }

    $(function () {
        $('#newStep').click(function () {
            if('${noOutNodes.size()}' == '0') {
                msger.err("没有可用进入节点，不能新建环节")
                return;
            }
            $('#stepType').combo('enable');
            $('#stepType').combobox('select', -1);
            $('#stepType').parent('div').css('color', 'red');

        })

        $('input[name=operation_code]').click(function () {
            var noticeDiv = $(this).parent().next('.noticeDiv');
            if ($(this).val() == '1') {
                noticeDiv.slideUp('slow');
            } else {
                noticeDiv.slideDown('slow');
            }
        })
        $('input[name=taskType]').click(function () {
            if($(this).val() == '1') {
                $('.sltExist').slideDown('slow');
//                $('.newTask').find('input,select').validatebox('readonly');
            } else {
                $('.sltExist').slideUp('slow');
//                $('.newTask').find('input,select').validatebox('readonly',false);
            }
        })

        //环节删除按钮
        $('.delStepBtn').click(function () {
            var that = $(this);
            $.messager.confirm('温馨提示', '确定要删除吗？', function (r) {
                if (r) {
                    $.get("${ctx}/aid/procdef/step/del?stepId=" + that.attr('stepId'), function (res) {
                        if (res.status == 1) {
                            $.messager.alert('错误', '删除环节失败', 'error');
                        } else {
                            msger.success("删除成功", function () {
                                location.href = '${ctx}/aid/procdef/update?planId=${param.planId}'
                            })
                        }
                    });
                }
            });
        });
        //环节选择按钮
        $('.stepBtn').click(function () {
            if ($(this).hasClass("l-btn-selected")) return;
            else {
                location.href = '${ctx}/aid/procdef/update?planId=${param.planId}&stepId=' + $(this).attr('stepId')
                    + '&stepType=' + $(this).attr('stepType');
            }
        })
        //环节类型下拉框
        $('#stepType').combobox({
            onChange: function (newVal, oldVal) {
                var cb = function () {
                    location.href = '${ctx}/aid/procdef/update?planId=${param.planId}&stepId=-1&stepType=' + oldVal;
                }
                if(newVal == 1 && ${noOutNodes.size() == 1 && noOutNodes.get(0).code == 0 ? 'true' : 'false'}) {
                    msger.err("启动环节不能是分支环节", cb)
                } else if(newVal == 3 && '${noOutNodes.size()}' < 2) {
                    msger.err("汇聚环节需要最少2个进入节点", cb);
                } else if(newVal == -1) {}
                else{
                    location.href = '${ctx}/aid/procdef/update?planId=${param.planId}&stepId=-1&stepType=' + newVal;
                }

            }
        })
    })
    function saveStep() {
        //validate
        var validate = true;
        $('.toValid').each(function () {
            if(!$(this).textbox('isValid')) {
                validate = false;
                var taskForm = $(this).parents('.taskForm');
                if(taskForm.size() != 0) {
                    $('#taskPanels').accordion('select', $('.taskForm').index(taskForm));
                }
                return false;
            }

        })
        if(!validate) {
            msger.tip('请确认表单填写正确！');
            return;
        }

        var params = {};
        params.planId = '${param.planId}';
        if (stepId != '-1') params.stepId = stepId;
        params.type = $('#stepType').val();
        params.lastCodes = '';
        $('input[name=lastCodes]').each(function () {
            params.lastCodes += $(this).val() + ',';
        })
        params.lastCodes = params.lastCodes.substring(0, params.lastCodes.length - 1);

        var taskJsonArr = [];
        $('.taskForm').each(function () {
            var taskJson = {};
            $.each($(this).serializeArray(), function (i, e) {
                if (e.name == 'notifiedIds') {
                    if (typeof taskJson[e.name] == 'undefined') {
                        taskJson[e.name] = [e.value];
                    } else {
                        taskJson[e.name].push(e.value)
                    }
                } else {
                    taskJson[e.name] = e.value;
                }
            })

            taskJsonArr.push(taskJson);
        })
        params.tasksJson = JSON.stringify(taskJsonArr);
        $.ajax({
            type: 'POST',
            url: '${ctx}/aid/procdef/step/save',
            dataType: 'json',
            data: params,
            success: function (res) {
                if (res.status == 1) {
                    $.messager.alert('错误', '保存环节失败', 'error');
                } else {
                    if(res.data.isOver == true) {
                        $('#procImg').attr('src', '${ctx}/acti/getProcDefImg.do?procDefId=' + res.data.procDefId);
                        $('#showProcImg').show();
                        $('#w').window('open');
                    } else {
                        msger.success("保存成功", function () {
                            location.href="${ctx}/aid/procdef/update?planId=${param.planId}";
                        })
                    }
                }
            }
        })
    }
    function addTaskPanel() {
        if ($('#taskPanels .accordion-header').size() >= 6) {
            msger.tip('环节的任务节点不应超过6个！')
            return;
        }
        $('#taskPanels').accordion('add', {
            title: '新增任务节点',
            content: '<div class="ph" style="padding:10px"></div>',
            tools: [{
                iconCls: 'icon-delete',
                handler: function (e) {
                    var index = $(e.target).closest('.accordion-header').index('#taskPanels .accordion-header');
                    $('#taskPanels').accordion('remove', index);
                    $('#taskPanels').accordion('select', index - 1);

                }
            }]
        });
    }
    function createSltLast() {
        if ($('.newSltLast').size() >= 6) {
            msger.tip('进入节点不应超过8个！')
            return;
        }
        var input = $('<input>', {style: 'width:80px;', class: 'newSltLast'});
        input.insertBefore('#addSltLast').combobox({
            valueField: 'code',
            textField: 'code',
            data: [],
            style: {
                marginLeft: 4
            },
            icons: [{
                iconCls: 'icon-delete', handler: function (e) {
                    $(e.data.target).combo('destroy');
                }
            }]
        });
        input.next().css({'margin-left': '4px'});
    }
</script>
</body>
</html>
